package com.yuan.leetcode.JianZhiOffer;

/**
 * Created by yuanhaowu
 * Time 2022/6/12 21:23
 * <p>
 * 输入一个矩阵，按照从外向里以顺时针的顺序依次打印出每一个数字。
 * <p>
 * 输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
 * 输出：[1,2,3,6,9,8,7,4,5]
 * <p>
 * 1 2 3
 * 4 5 6 -> 1 2 3 6 9 8 7 4 5
 * 7 8 9
 */
public class offer29 {
    public int[] spiralOrder(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return new int[0];
        }
        //设置边界
        int left = 0, right = matrix[0].length - 1, top = 0, bottom = matrix.length - 1;
        //注意数组的大小
        int[] nums = new int[(right + 1) * (bottom + 1)];
        int count = 0;
        while (true) {
            //左->右
            for (int i = left; i <= right; i++) {
                nums[count++] = matrix[top][i];
            }
            if (++top > bottom) {
                break;
            }
            //上->下
            for (int i = top; i <= bottom; i++) {
                nums[count++] = matrix[i][right];
            }
            if (--right < left) {
                break;
            }
            //右->左
            for (int i = right; i >= left; i--) {
                nums[count++] = matrix[bottom][i];
            }
            if (--bottom < top) {
                break;
            }
            //下->上
            for (int i = bottom; i >= top; i--) {
                nums[count++] = matrix[i][left];
            }
            if (++left > right) {
                break;
            }
        }
        return nums;
    }
}
